﻿/*----------------------------------------------------------------
  //Copyright (C) 2012 赵国伟
  //文件功能描述：任务管理
  //创建人：赵国伟
  //生成时间：2012/04/17 16:15:00
//----------------------------------------------------------------*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.IO;
using System.Data;

using NVelocity;
using NVelocity.App;
using NVelocity.Context;
using NVelocity.Runtime;

using Shopping.Common;
using Shopping.Model;
using Shopping.DAL;

namespace Shopping.BLL
{
    public class TasksManage
    {
        private readonly DALTasks dalTask = new DALTasks();

        #region "查询一条任务信息 by 赵国伟 2012-04-18"
        /// <summary>
        /// 查询一条任务信息
        /// </summary>
        /// <param name="taskId"></param>
        /// <returns></returns>
        public Tasks GetTaskInfo(int taskId)
        {
            return dalTask.GetModel(taskId);
        }

        public TaskInfo GetTask(int taskId)
        {
            Tasks s = dalTask.GetModel(taskId);
            TaskInfo t = null;
            if (s != null)
            {
                t = new TaskInfo();
                t.Task = s;
                string templatePath = Config.Template_Folder;
                string targetPath = Config.AutoGenerate_Folder;
                if (!Config.Template_Folder.EndsWith("\\"))
                    templatePath += "\\";
                if (!Config.AutoGenerate_Folder.EndsWith("\\"))
                    targetPath += "\\";
                t.TemplateFile = templatePath + t.Task.TemplateUrl.Replace("/", "\\");
                t.TargetFile = targetPath + t.Task.TargetUrl.Replace("/", "\\");
            }
            return t;
        }
        #endregion

        #region "删除一条任务 by 赵国伟 2012-04-18"
        /// <summary>
        /// 删除一条任务
        /// </summary>
        /// <param name="taskID"></param>
        /// <returns></returns>
        public ReturnValue Delete(int taskID)
        {
            ReturnValue ret = new ReturnValue();
            if (dalTask.Delete(taskID) > 0)
            {
                ret.Result = ResultType.Success;
                ret.Message = "删除成功！";
            }
            return ret;
        }
        #endregion

        #region "保存系统任务；by 赵国伟 2012-04-18"
        /// <summary>
        /// 保存系统任务；
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public  ReturnValue Save(Tasks t)
        {
            ReturnValue ret = new ReturnValue();
            if (dalTask.QueryList(1, "TaskName='" + t.TaskName + "' and TaskID<>" + t.TaskID, "") != null)
            {
                ret.Message = "任务名称重复！";
                return ret;
            }
            t.CreateDate = DateTime.Now;
            t.LastModifyDate = DateTime.Now;
            if (t.TaskID <= 0)
            {
                if (dalTask.Add(t) > 0)
                {
                    ret.Result = ResultType.Success;
                    ret.Message = "保存成功！";
                }
            }
            else
            {
                Tasks o = dalTask.GetModel(t.TaskID);
                t.CreateDate = o.CreateDate;
                t.IsExecuteSuc = o.IsExecuteSuc;
                t.LastExecuteDate = o.LastExecuteDate;
                t.Reason = o.Reason;
                if (dalTask.Update(t) > 0)
                {
                    ret.Result = ResultType.Success;
                    ret.Message = "保存成功！";
                }
            }
            return ret;
        }
        #endregion

        #region "查询所有的系统任务； by 赵国伟 2012-04-18"
        /// <summary>
        /// 查询所有的系统任务；
        /// </summary>
        /// <returns></returns>
        public List<TaskInfo> QueryAllTask()
        {
            List<Tasks> source = dalTask.QueryList("", "");
            List<TaskInfo> target = null;
            if (source != null)
            {
                target = new List<TaskInfo>();
                string templatePath = Config.Template_Folder;
                string targetPath = Config.AutoGenerate_Folder;
                if (!Config.Template_Folder.EndsWith("\\"))
                    templatePath += "\\";
                if (!Config.AutoGenerate_Folder.EndsWith("\\"))
                    targetPath += "\\";
                foreach (Tasks s in source)
                {
                    TaskInfo t = new TaskInfo();
                    t.Task = s;
                    t.TemplateFile = templatePath + t.Task.TemplateUrl.Replace("/", "\\");
                    t.TargetFile = targetPath + t.Task.TargetUrl.Replace("/", "\\");
                    target.Add(t);
                }
            }
            return target;
        }
        #endregion

        #region "执行一条任务； by 赵国伟 2012-04-18"


        public ReturnValue RunTask(int taskId)
        {
           return  RunTask(GetTask(taskId));
        }

        public ReturnValue RunTask(TaskInfo t)
        {
            ReturnValue ret = ExecuteTask(t);

            t.Task.IsExecuteSuc = ret.IsSucc;
            t.Task.LastExecuteDate = DateTime.Now;
            if (!ret.IsSucc)
                t.Task.Reason = ret.Message;
            dalTask.Update(t.Task);
            return ret;
        }

      
        /// <summary>
        /// 具体执行一条任务；
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        private ReturnValue ExecuteTask(TaskInfo t)
        {
            ReturnValue ret = new ReturnValue();
            if (!File.Exists(t.TemplateFile))
            {
               ret.Message = "模板文件不存在！";
               return ret;
            }

            #region "读取数据源数据；"
            DataTable dt = null;
            try
            {
                dt = DALHelper.Query(t.Task.SQL);
            }
            catch (Exception e)
            {
                ret.Message = "数据读取失败！";
                return ret;
            }
            #endregion
          
            IContext context = new VelocityContext();
            context.Put("Utility", new Utility());
            context.Put("DataList", dt.Rows);

            try
            {
                Utility.WriteToFileEx(t.TargetFile, VelocityHelper.GetMergeContent(t.Task.TemplateUrl.Replace("/","\\"), context),"utf-8"); //根据模板生成内容；
            }
            catch (Exception e)
            {
                ret.Message = "生成失败(" + e.Message + ")";
                return ret;
            }
            ret.Result = ResultType.Success;
            ret.Message = "生成成功！";
            return ret;
        }
        #endregion



    }
}
